{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp models.timemixer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TimeMixer\n",
    "\n",
    "Seasonal and trend components exhibit significantly different characteristics in time series, and different scales of the time series reflect different properties, with seasonal characteristics being more pronounced at a fine-grained micro scale and trend characteristics being more pronounced at a coarse macro scale, it is therefore necessary to decouple seasonal and trend components at different scales. As such, TimeMixer is an MLP-based architecture with Past-Decomposable-Mixing (PDM) and Future-Multipredictor-Mixing (FMM) blocks to take full advantage of disentangled multiscale series in both past extraction and future prediction phases.\n",
    "\n",
    "**References**<br>\n",
    "[Shiyu Wang, Haixu Wu, Xiaoming Shi, Tengge Hu, Huakun Luo, Lintao Ma, James Y. Zhang, Jun Zhou.\"TimeMixer: Decomposable Multiscale Mixing For Time Series Forecasting\"](https://openreview.net/pdf?id=7oLshfEIC2)<br>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Figure 1. Architecture of SOFTS.](imgs_models/timemixer.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "import math\n",
    "import numpy as np\n",
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "\n",
    "from neuralforecast.common._base_model import BaseModel\n",
    "from neuralforecast.common._modules import PositionalEmbedding, TokenEmbedding, TemporalEmbedding, SeriesDecomp, RevIN\n",
    "from neuralforecast.losses.pytorch import MAE\n",
    "from typing import Optional"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import logging\n",
    "import warnings\n",
    "from fastcore.test import test_eq\n",
    "from nbdev.showdoc import show_doc\n",
    "from neuralforecast.common._model_checks import check_model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Embedding"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "\n",
    "class DataEmbedding_wo_pos(nn.Module):\n",
    "    \"\"\"\n",
    "    DataEmbedding_wo_pos\n",
    "    \"\"\"\n",
    "    def __init__(self, c_in, d_model, dropout=0.1, embed_type='fixed', freq='h'):\n",
    "        super(DataEmbedding_wo_pos, self).__init__()\n",
    "\n",
    "        self.value_embedding = TokenEmbedding(c_in=c_in, hidden_size=d_model)\n",
    "        self.position_embedding = PositionalEmbedding(hidden_size=d_model)\n",
    "        self.temporal_embedding = TemporalEmbedding(d_model=d_model, embed_type=embed_type,\n",
    "                                                    freq=freq)\n",
    "        self.dropout = nn.Dropout(p=dropout)\n",
    "\n",
    "    def forward(self, x, x_mark):\n",
    "        if x is None and x_mark is not None:\n",
    "            return self.temporal_embedding(x_mark)\n",
    "        if x_mark is None:\n",
    "            x = self.value_embedding(x)\n",
    "        else:\n",
    "            x = self.value_embedding(x) + self.temporal_embedding(x_mark)\n",
    "        return self.dropout(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### DFT decomposition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "\n",
    "class DFT_series_decomp(nn.Module):\n",
    "    \"\"\"\n",
    "    Series decomposition block\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, top_k):\n",
    "        super(DFT_series_decomp, self).__init__()\n",
    "        self.top_k = top_k\n",
    "\n",
    "    def forward(self, x):\n",
    "        xf = torch.fft.rfft(x)\n",
    "        freq = abs(xf)\n",
    "        freq[0] = 0\n",
    "        top_k_freq, top_list = torch.topk(freq, self.top_k)\n",
    "        xf[freq <= top_k_freq.min()] = 0\n",
    "        x_season = torch.fft.irfft(xf)\n",
    "        x_trend = x - x_season\n",
    "        return x_season, x_trend"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Mixing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "\n",
    "class MultiScaleSeasonMixing(nn.Module):\n",
    "    \"\"\"\n",
    "    Bottom-up mixing season pattern\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, seq_len, down_sampling_window, down_sampling_layers):\n",
    "        super(MultiScaleSeasonMixing, self).__init__()\n",
    "\n",
    "        self.down_sampling_layers = torch.nn.ModuleList(\n",
    "            [\n",
    "                nn.Sequential(\n",
    "                    torch.nn.Linear(\n",
    "                        math.ceil(seq_len // (down_sampling_window ** i)),\n",
    "                        math.ceil(seq_len // (down_sampling_window ** (i + 1))),\n",
    "                    ),\n",
    "                    nn.GELU(),\n",
    "                    torch.nn.Linear(\n",
    "                        math.ceil(seq_len // (down_sampling_window ** (i + 1))),\n",
    "                        math.ceil(seq_len // (down_sampling_window ** (i + 1))),\n",
    "                    ),\n",
    "\n",
    "                )\n",
    "                for i in range(down_sampling_layers)\n",
    "            ]\n",
    "        )\n",
    "\n",
    "    def forward(self, season_list):\n",
    "\n",
    "        # mixing high->low\n",
    "        out_high = season_list[0]\n",
    "        out_low = season_list[1]\n",
    "        out_season_list = [out_high.permute(0, 2, 1)]\n",
    "\n",
    "        for i in range(len(season_list) - 1):\n",
    "            out_low_res = self.down_sampling_layers[i](out_high)\n",
    "            out_low = out_low + out_low_res\n",
    "            out_high = out_low\n",
    "            if i + 2 <= len(season_list) - 1:\n",
    "                out_low = season_list[i + 2]\n",
    "            out_season_list.append(out_high.permute(0, 2, 1))\n",
    "\n",
    "        return out_season_list\n",
    "\n",
    "\n",
    "class MultiScaleTrendMixing(nn.Module):\n",
    "    \"\"\"\n",
    "    Top-down mixing trend pattern\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, seq_len, down_sampling_window, down_sampling_layers):\n",
    "        super(MultiScaleTrendMixing, self).__init__()\n",
    "\n",
    "        self.up_sampling_layers = torch.nn.ModuleList(\n",
    "            [\n",
    "                nn.Sequential(\n",
    "                    torch.nn.Linear(\n",
    "                        math.ceil(seq_len / (down_sampling_window ** (i + 1))),\n",
    "                        math.ceil(seq_len / (down_sampling_window ** i)),\n",
    "                    ),\n",
    "                    nn.GELU(),\n",
    "                    torch.nn.Linear(\n",
    "                        math.ceil(seq_len / (down_sampling_window ** i)),\n",
    "                        math.ceil(seq_len / (down_sampling_window ** i)),\n",
    "                    ),\n",
    "                )\n",
    "                for i in reversed(range(down_sampling_layers))\n",
    "            ])\n",
    "\n",
    "    def forward(self, trend_list):\n",
    "\n",
    "        # mixing low->high\n",
    "        trend_list_reverse = trend_list.copy()\n",
    "        trend_list_reverse.reverse()\n",
    "        out_low = trend_list_reverse[0]\n",
    "        out_high = trend_list_reverse[1]\n",
    "        out_trend_list = [out_low.permute(0, 2, 1)]\n",
    "\n",
    "        for i in range(len(trend_list_reverse) - 1):\n",
    "            out_high_res = self.up_sampling_layers[i](out_low)\n",
    "            out_high = out_high + out_high_res\n",
    "            out_low = out_high\n",
    "            if i + 2 <= len(trend_list_reverse) - 1:\n",
    "                out_high = trend_list_reverse[i + 2]\n",
    "            out_trend_list.append(out_low.permute(0, 2, 1))\n",
    "\n",
    "        out_trend_list.reverse()\n",
    "        return out_trend_list\n",
    "\n",
    "\n",
    "class PastDecomposableMixing(nn.Module):\n",
    "    \"\"\"\n",
    "    PastDecomposableMixing\n",
    "    \"\"\"\n",
    "    def __init__(self, seq_len, pred_len, down_sampling_window, down_sampling_layers, \n",
    "                 d_model, dropout, channel_independence, decomp_method, d_ff, moving_avg, top_k):\n",
    "        super(PastDecomposableMixing, self).__init__()\n",
    "        self.seq_len = seq_len\n",
    "        self.pred_len = pred_len\n",
    "        self.down_sampling_window = down_sampling_window\n",
    "        self.down_sampling_layers = down_sampling_layers\n",
    "\n",
    "        self.layer_norm = nn.LayerNorm(d_model)\n",
    "        self.dropout = nn.Dropout(dropout)\n",
    "        self.channel_independence = channel_independence\n",
    "\n",
    "        if decomp_method == 'moving_avg':\n",
    "            self.decompsition = SeriesDecomp(moving_avg)\n",
    "        elif decomp_method == \"dft_decomp\":\n",
    "            self.decompsition = DFT_series_decomp(top_k)\n",
    "        else:\n",
    "            raise ValueError('decompsition is error')\n",
    "\n",
    "        if self.channel_independence == 0:\n",
    "            self.cross_layer = nn.Sequential(\n",
    "                nn.Linear(in_features=d_model, out_features=d_ff),\n",
    "                nn.GELU(),\n",
    "                nn.Linear(in_features=d_ff, out_features=d_model),\n",
    "            )\n",
    "\n",
    "        # Mixing season\n",
    "        self.mixing_multi_scale_season = MultiScaleSeasonMixing(self.seq_len, self.down_sampling_window, self.down_sampling_layers)\n",
    "\n",
    "        # Mxing trend\n",
    "        self.mixing_multi_scale_trend = MultiScaleTrendMixing(self.seq_len, self.down_sampling_window, self.down_sampling_layers)\n",
    "\n",
    "        self.out_cross_layer = nn.Sequential(\n",
    "            nn.Linear(in_features=d_model, out_features=d_ff),\n",
    "            nn.GELU(),\n",
    "            nn.Linear(in_features=d_ff, out_features=d_model),\n",
    "        )\n",
    "\n",
    "    def forward(self, x_list):\n",
    "        length_list = []\n",
    "        for x in x_list:\n",
    "            _, T, _ = x.size()\n",
    "            length_list.append(T)\n",
    "\n",
    "        # Decompose to obtain the season and trend\n",
    "        season_list = []\n",
    "        trend_list = []\n",
    "        for x in x_list:\n",
    "            season, trend = self.decompsition(x)\n",
    "            if self.channel_independence == 0:\n",
    "                season = self.cross_layer(season)\n",
    "                trend = self.cross_layer(trend)\n",
    "            season_list.append(season.permute(0, 2, 1))\n",
    "            trend_list.append(trend.permute(0, 2, 1))\n",
    "\n",
    "        # bottom-up season mixing\n",
    "        out_season_list = self.mixing_multi_scale_season(season_list)\n",
    "        # top-down trend mixing\n",
    "        out_trend_list = self.mixing_multi_scale_trend(trend_list)\n",
    "\n",
    "        out_list = []\n",
    "        for ori, out_season, out_trend, length in zip(x_list, out_season_list, out_trend_list,\n",
    "                                                      length_list):\n",
    "            out = out_season + out_trend\n",
    "            if self.channel_independence:\n",
    "                out = ori + self.out_cross_layer(out)\n",
    "            out_list.append(out[:, :length, :])\n",
    "        return out_list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "\n",
    "class TimeMixer(BaseModel):\n",
    "    \"\"\" TimeMixer\n",
    "    **Parameters**<br>\n",
    "    `h`: int, Forecast horizon. <br>\n",
    "    `input_size`: int, autorregresive inputs size, y=[1,2,3,4] input_size=2 -> y_[t-2:t]=[1,2].<br>\n",
    "    `n_series`: int, number of time-series.<br>\n",
    "    `stat_exog_list`: str list, static exogenous columns.<br>\n",
    "    `hist_exog_list`: str list, historic exogenous columns.<br>\n",
    "    `futr_exog_list`: str list, future exogenous columns.<br>\n",
    "    `d_model`: int, dimension of the model.<br>\n",
    "    `d_ff`: int, dimension of the fully-connected network.<br>\n",
    "    `dropout`: float, dropout rate.<br>\n",
    "    `e_layers`: int, number of encoder layers.<br>\n",
    "    `top_k`: int, number of selected frequencies.<br>\n",
    "    `decomp_method`: str, method of series decomposition [moving_avg, dft_decomp].<br>\n",
    "    `moving_avg`: int, window size of moving average.<br>\n",
    "    `channel_independence`: int, 0: channel dependence, 1: channel independence.<br>\n",
    "    `down_sampling_layers`: int, number of downsampling layers.<br>\n",
    "    `down_sampling_window`: int, size of downsampling window.<br>\n",
    "    `down_sampling_method`: str, down sampling method [avg, max, conv].<br>\n",
    "    `use_norm`: bool, whether to normalize or not.<br>\n",
    "\t`decoder_input_size_multiplier`: float = 0.5.<br>\n",
    "    `loss`: PyTorch module, instantiated train loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `valid_loss`: PyTorch module=`loss`, instantiated valid loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `max_steps`: int=1000, maximum number of training steps.<br>\n",
    "    `learning_rate`: float=1e-3, Learning rate between (0, 1).<br>\n",
    "    `num_lr_decays`: int=-1, Number of learning rate decays, evenly distributed across max_steps.<br>\n",
    "    `early_stop_patience_steps`: int=-1, Number of validation iterations before early stopping.<br>\n",
    "    `val_check_steps`: int=100, Number of training steps between every validation loss check.<br>\n",
    "    `batch_size`: int=32, number of different series in each batch.<br>\n",
    "    `valid_batch_size`: int=None, number of different series in each validation and test batch, if None uses batch_size.<br>\n",
    "    `windows_batch_size`: int=32, number of windows to sample in each training batch, default uses all.<br>\n",
    "    `inference_windows_batch_size`: int=32, number of windows to sample in each inference batch, -1 uses all.<br>\n",
    "    `start_padding_enabled`: bool=False, if True, the model will pad the time series with zeros at the beginning, by input size.<br>\n",
    "    `step_size`: int=1, step size between each window of temporal data.<br>\n",
    "    `scaler_type`: str='identity', type of scaler for temporal inputs normalization see [temporal scalers](https://nixtla.github.io/neuralforecast/common.scalers.html).<br>\n",
    "    `random_seed`: int=1, random_seed for pytorch initializer and numpy generators.<br>\n",
    "    `drop_last_loader`: bool=False, if True `TimeSeriesDataLoader` drops last non-full batch.<br>\n",
    "    `alias`: str, optional,  Custom name of the model.<br>\n",
    "    `optimizer`: Subclass of 'torch.optim.Optimizer', optional, user specified optimizer instead of the default choice (Adam).<br>\n",
    "    `optimizer_kwargs`: dict, optional, list of parameters used by the user specified `optimizer`.<br>\n",
    "    `lr_scheduler`: Subclass of 'torch.optim.lr_scheduler.LRScheduler', optional, user specified lr_scheduler instead of the default choice (StepLR).<br>\n",
    "    `lr_scheduler_kwargs`: dict, optional, list of parameters used by the user specified `lr_scheduler`.<br>\n",
    "    `dataloader_kwargs`: dict, optional, list of parameters passed into the PyTorch Lightning dataloader by the `TimeSeriesDataLoader`. <br>\n",
    "    `**trainer_kwargs`: keyword trainer arguments inherited from [PyTorch Lighning's trainer](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.trainer.trainer.Trainer.html?highlight=trainer).<br>\n",
    "\n",
    "    **References**<br>\n",
    "    [Shiyu Wang, Haixu Wu, Xiaoming Shi, Tengge Hu, Huakun Luo, Lintao Ma, James Y. Zhang, Jun Zhou.\"TimeMixer: Decomposable Multiscale Mixing For Time Series Forecasting\"](https://openreview.net/pdf?id=7oLshfEIC2)<br>\n",
    "    \"\"\"\n",
    "\n",
    "    # Class attributes\n",
    "    EXOGENOUS_FUTR = False\n",
    "    EXOGENOUS_HIST = False\n",
    "    EXOGENOUS_STAT = False\n",
    "    MULTIVARIATE = True    # If the model produces multivariate forecasts (True) or univariate (False)\n",
    "    RECURRENT = False       # If the model produces forecasts recursively (True) or direct (False)\n",
    "\n",
    "    def __init__(self,\n",
    "                 h,\n",
    "                 input_size,\n",
    "                 n_series,\n",
    "                 stat_exog_list = None,\n",
    "                 hist_exog_list = None,\n",
    "                 futr_exog_list = None,\n",
    "                 d_model: int = 32,\n",
    "                 d_ff: int = 32,\n",
    "                 dropout: float = 0.1,\n",
    "                 e_layers: int = 4,\n",
    "                 top_k: int = 5,\n",
    "                 decomp_method: str = 'moving_avg',\n",
    "                 moving_avg: int = 25,\n",
    "                 channel_independence: int = 0,\n",
    "                 down_sampling_layers: int = 1,\n",
    "                 down_sampling_window: int = 2,\n",
    "                 down_sampling_method: str = 'avg',\n",
    "                 use_norm: bool = True,\n",
    "                 decoder_input_size_multiplier: float = 0.5,\n",
    "                 loss = MAE(),\n",
    "                 valid_loss = None,\n",
    "                 max_steps: int = 1000,\n",
    "                 learning_rate: float = 1e-3,\n",
    "                 num_lr_decays: int = -1,\n",
    "                 early_stop_patience_steps: int =-1,\n",
    "                 val_check_steps: int = 100,\n",
    "                 batch_size: int = 32,\n",
    "                 valid_batch_size: Optional[int] = None,\n",
    "                 windows_batch_size = 32,\n",
    "                 inference_windows_batch_size = 32,\n",
    "                 start_padding_enabled = False,\n",
    "                 step_size: int = 1,\n",
    "                 scaler_type: str = 'identity',\n",
    "                 random_seed: int = 1,\n",
    "                 drop_last_loader: bool = False,\n",
    "                 alias: Optional[str] = None,\n",
    "                 optimizer = None,\n",
    "                 optimizer_kwargs = None,\n",
    "                 lr_scheduler = None,\n",
    "                 lr_scheduler_kwargs = None,    \n",
    "                 dataloader_kwargs = None,        \n",
    "                 **trainer_kwargs):\n",
    "        \n",
    "        super(TimeMixer, self).__init__(h=h,\n",
    "                                    input_size=input_size,\n",
    "                                    n_series=n_series,\n",
    "                                    stat_exog_list = stat_exog_list,\n",
    "                                    futr_exog_list = futr_exog_list,\n",
    "                                    hist_exog_list = hist_exog_list,\n",
    "                                    loss=loss,\n",
    "                                    valid_loss=valid_loss,\n",
    "                                    max_steps=max_steps,\n",
    "                                    learning_rate=learning_rate,\n",
    "                                    num_lr_decays=num_lr_decays,\n",
    "                                    early_stop_patience_steps=early_stop_patience_steps,\n",
    "                                    val_check_steps=val_check_steps,\n",
    "                                    batch_size=batch_size,\n",
    "                                    valid_batch_size=valid_batch_size,\n",
    "                                    windows_batch_size=windows_batch_size,\n",
    "                                    inference_windows_batch_size=inference_windows_batch_size,\n",
    "                                    start_padding_enabled=start_padding_enabled,\n",
    "                                    step_size=step_size,\n",
    "                                    scaler_type=scaler_type,\n",
    "                                    random_seed=random_seed,\n",
    "                                    drop_last_loader=drop_last_loader,\n",
    "                                    alias=alias,\n",
    "                                    optimizer=optimizer,\n",
    "                                    optimizer_kwargs=optimizer_kwargs,\n",
    "                                    lr_scheduler=lr_scheduler,\n",
    "                                    lr_scheduler_kwargs=lr_scheduler_kwargs,\n",
    "                                    dataloader_kwargs=dataloader_kwargs,\n",
    "                                    **trainer_kwargs)\n",
    "        \n",
    "        self.label_len = int(np.ceil(input_size * decoder_input_size_multiplier))\n",
    "        if (self.label_len >= input_size) or (self.label_len <= 0):\n",
    "            raise Exception(f'Check decoder_input_size_multiplier={decoder_input_size_multiplier}, range (0,1)')\n",
    "        \n",
    "        self.h = h\n",
    "        self.input_size = input_size\n",
    "        self.e_layers = e_layers\n",
    "        self.d_model = d_model\n",
    "        self.d_ff = d_ff\n",
    "        self.dropout = dropout\n",
    "        self.top_k = top_k\n",
    "\n",
    "        self.use_norm = use_norm\n",
    "\n",
    "        self.use_future_temporal_feature = 0\n",
    "        if futr_exog_list is not None:\n",
    "            self.use_future_temporal_feature = 1\n",
    "\n",
    "        self.decomp_method = decomp_method\n",
    "        self.moving_avg = moving_avg\n",
    "        self.channel_independence = channel_independence\n",
    "\n",
    "        self.down_sampling_layers = down_sampling_layers\n",
    "        self.down_sampling_window = down_sampling_window\n",
    "        self.down_sampling_method = down_sampling_method\n",
    "\n",
    "        self.pdm_blocks = nn.ModuleList([PastDecomposableMixing(self.input_size, self.h, self.down_sampling_window, self.down_sampling_layers, self.d_model, self.dropout, self.channel_independence, self.decomp_method, self.d_ff, self.moving_avg, self.top_k)\n",
    "                                         for _ in range(self.e_layers)])\n",
    "        \n",
    "        self.preprocess = SeriesDecomp(self.moving_avg)\n",
    "        self.enc_in = n_series\n",
    "        self.c_out = n_series\n",
    "\n",
    "        if self.channel_independence == 1:\n",
    "            self.enc_embedding = DataEmbedding_wo_pos(1, self.d_model, self.dropout)\n",
    "        else:\n",
    "            self.enc_embedding = DataEmbedding_wo_pos(self.enc_in, self.d_model, self.dropout)\n",
    "\n",
    "        self.normalize_layers = torch.nn.ModuleList(\n",
    "            [\n",
    "                RevIN(self.enc_in, affine=True, non_norm=False if self.use_norm else True)\n",
    "                for i in range(self.down_sampling_layers + 1)\n",
    "            ]\n",
    "        )\n",
    "\n",
    "        self.predict_layers = torch.nn.ModuleList(\n",
    "            [\n",
    "                torch.nn.Linear(\n",
    "                    math.ceil(self.input_size // (self.down_sampling_window ** i)),\n",
    "                    self.h,\n",
    "                )\n",
    "                for i in range(self.down_sampling_layers + 1)\n",
    "            ]\n",
    "        )\n",
    "\n",
    "        if self.channel_independence == 1:\n",
    "            self.projection_layer = nn.Linear(\n",
    "                self.d_model, 1, bias=True)\n",
    "        else:\n",
    "            self.projection_layer = nn.Linear(\n",
    "                self.d_model, self.c_out, bias=True)\n",
    "\n",
    "            self.out_res_layers = torch.nn.ModuleList([\n",
    "                torch.nn.Linear(\n",
    "                    self.input_size // (self.down_sampling_window ** i),\n",
    "                    self.input_size // (self.down_sampling_window ** i),\n",
    "                )\n",
    "                for i in range(self.down_sampling_layers + 1)\n",
    "            ])\n",
    "\n",
    "            self.regression_layers = torch.nn.ModuleList(\n",
    "                [\n",
    "                    torch.nn.Linear(\n",
    "                        self.input_size // (self.down_sampling_window ** i),\n",
    "                        self.h,\n",
    "                    )\n",
    "                    for i in range(self.down_sampling_layers + 1)\n",
    "                ]\n",
    "            )\n",
    "        \n",
    "        if self.loss.outputsize_multiplier > 1:\n",
    "            self.distr_output = nn.Linear(self.n_series, self.n_series * self.loss.outputsize_multiplier)\n",
    "\n",
    "    def out_projection(self, dec_out, i, out_res):\n",
    "        dec_out = self.projection_layer(dec_out)\n",
    "        out_res = out_res.permute(0, 2, 1)\n",
    "        out_res = self.out_res_layers[i](out_res)\n",
    "        out_res = self.regression_layers[i](out_res).permute(0, 2, 1)\n",
    "        dec_out = dec_out + out_res\n",
    "        return dec_out\n",
    "    \n",
    "    def pre_enc(self, x_list):\n",
    "        if self.channel_independence == 1:\n",
    "            return (x_list, None)\n",
    "        else:\n",
    "            out1_list = []\n",
    "            out2_list = []\n",
    "            for x in x_list:\n",
    "                x_1, x_2 = self.preprocess(x)\n",
    "                out1_list.append(x_1)\n",
    "                out2_list.append(x_2)\n",
    "            return (out1_list, out2_list)\n",
    "        \n",
    "    def __multi_scale_process_inputs(self, x_enc, x_mark_enc):\n",
    "        if self.down_sampling_method == 'max':\n",
    "            down_pool = torch.nn.MaxPool1d(self.down_sampling_window, return_indices=False)\n",
    "        elif self.down_sampling_method == 'avg':\n",
    "            down_pool = torch.nn.AvgPool1d(self.down_sampling_window)\n",
    "        elif self.down_sampling_method == 'conv':\n",
    "            padding = 1\n",
    "            down_pool = nn.Conv1d(in_channels=self.enc_in, out_channels=self.enc_in,\n",
    "                                  kernel_size=3, padding=padding,\n",
    "                                  stride=self.down_sampling_window,\n",
    "                                  padding_mode='circular',\n",
    "                                  bias=False)\n",
    "        else:\n",
    "            return x_enc, x_mark_enc\n",
    "        # B,T,C -> B,C,T\n",
    "        x_enc = x_enc.permute(0, 2, 1)\n",
    "\n",
    "        x_enc_ori = x_enc\n",
    "        x_mark_enc_mark_ori = x_mark_enc\n",
    "\n",
    "        x_enc_sampling_list = []\n",
    "        x_mark_sampling_list = []\n",
    "        x_enc_sampling_list.append(x_enc.permute(0, 2, 1))\n",
    "        x_mark_sampling_list.append(x_mark_enc)\n",
    "\n",
    "        for i in range(self.down_sampling_layers):\n",
    "            x_enc_sampling = down_pool(x_enc_ori)\n",
    "\n",
    "            x_enc_sampling_list.append(x_enc_sampling.permute(0, 2, 1))\n",
    "            x_enc_ori = x_enc_sampling\n",
    "\n",
    "            if x_mark_enc_mark_ori is not None:\n",
    "                x_mark_sampling_list.append(x_mark_enc_mark_ori[:, ::self.down_sampling_window, :])\n",
    "                x_mark_enc_mark_ori = x_mark_enc_mark_ori[:, ::self.down_sampling_window, :]\n",
    "\n",
    "        x_enc = x_enc_sampling_list\n",
    "        if x_mark_enc_mark_ori is not None:\n",
    "            x_mark_enc = x_mark_sampling_list\n",
    "        else:\n",
    "            x_mark_enc = x_mark_enc\n",
    "\n",
    "        return x_enc, x_mark_enc\n",
    "    \n",
    "    def forecast(self, x_enc, x_mark_enc, x_mark_dec):\n",
    "\n",
    "        if self.use_future_temporal_feature:\n",
    "            if self.channel_independence == 1:\n",
    "                B, T, N = x_enc.size()\n",
    "                x_mark_dec = x_mark_dec.repeat(N, 1, 1)\n",
    "                self.x_mark_dec = self.enc_embedding(None, x_mark_dec)\n",
    "            else:\n",
    "                self.x_mark_dec = self.enc_embedding(None, x_mark_dec)\n",
    "\n",
    "        x_enc, x_mark_enc = self.__multi_scale_process_inputs(x_enc, x_mark_enc)\n",
    "\n",
    "        x_list = []\n",
    "        x_mark_list = []\n",
    "        if x_mark_enc is not None:\n",
    "            for i, x, x_mark in zip(range(len(x_enc)), x_enc, x_mark_enc):\n",
    "                B, T, N = x.size()\n",
    "                x = self.normalize_layers[i](x, 'norm')\n",
    "                if self.channel_independence == 1:\n",
    "                    x = x.permute(0, 2, 1).contiguous().reshape(B * N, T, 1)\n",
    "                    x_mark = x_mark.repeat(N, 1, 1)\n",
    "                x_list.append(x)\n",
    "                x_mark_list.append(x_mark)\n",
    "        else:\n",
    "            for i, x in zip(range(len(x_enc)), x_enc, ):\n",
    "                B, T, N = x.size()\n",
    "                x = self.normalize_layers[i](x, 'norm')\n",
    "                if self.channel_independence == 1:\n",
    "                    x = x.permute(0, 2, 1).contiguous().reshape(B * N, T, 1)\n",
    "                x_list.append(x)\n",
    "\n",
    "        # embedding\n",
    "        enc_out_list = []\n",
    "        x_list = self.pre_enc(x_list)\n",
    "        if x_mark_enc is not None:\n",
    "            for i, x, x_mark in zip(range(len(x_list[0])), x_list[0], x_mark_list):\n",
    "                enc_out = self.enc_embedding(x, x_mark)  # [B,T,C]\n",
    "                enc_out_list.append(enc_out)\n",
    "        else:\n",
    "            for i, x in zip(range(len(x_list[0])), x_list[0]):\n",
    "                enc_out = self.enc_embedding(x, None)  # [B,T,C]\n",
    "                enc_out_list.append(enc_out)\n",
    "\n",
    "        # Past Decomposable Mixing as encoder for past\n",
    "        for i in range(self.e_layers):\n",
    "            enc_out_list = self.pdm_blocks[i](enc_out_list)\n",
    "\n",
    "        # Future Multipredictor Mixing as decoder for future\n",
    "        dec_out_list = self.future_multi_mixing(B, enc_out_list, x_list)\n",
    "\n",
    "        dec_out = torch.stack(dec_out_list, dim=-1).sum(-1)\n",
    "        dec_out = self.normalize_layers[0](dec_out, 'denorm')\n",
    "        return dec_out\n",
    "    \n",
    "    def future_multi_mixing(self, B, enc_out_list, x_list):\n",
    "        dec_out_list = []\n",
    "        if self.channel_independence == 1:\n",
    "            x_list = x_list[0]\n",
    "            for i, enc_out in zip(range(len(x_list)), enc_out_list):\n",
    "                dec_out = self.predict_layers[i](enc_out.permute(0, 2, 1)).permute(\n",
    "                    0, 2, 1)  # align temporal dimension\n",
    "                if self.use_future_temporal_feature:\n",
    "                    dec_out = dec_out + self.x_mark_dec\n",
    "                    dec_out = self.projection_layer(dec_out)\n",
    "                else:\n",
    "                    dec_out = self.projection_layer(dec_out)\n",
    "                dec_out = dec_out.reshape(B, self.c_out, self.h).permute(0, 2, 1).contiguous()\n",
    "                dec_out_list.append(dec_out)\n",
    "\n",
    "        else:\n",
    "            for i, enc_out, out_res in zip(range(len(x_list[0])), enc_out_list, x_list[1]):\n",
    "                dec_out = self.predict_layers[i](enc_out.permute(0, 2, 1)).permute(\n",
    "                    0, 2, 1)  # align temporal dimension\n",
    "                dec_out = self.out_projection(dec_out, i, out_res)\n",
    "                dec_out_list.append(dec_out)\n",
    "\n",
    "        return dec_out_list\n",
    "    \n",
    "    def forward(self, windows_batch):\n",
    "        insample_y = windows_batch['insample_y']\n",
    "        futr_exog = windows_batch['futr_exog']\n",
    "\n",
    "        if self.futr_exog_size > 0:\n",
    "            x_mark_enc = futr_exog[:, :, :self.input_size, :]\n",
    "            x_mark_dec = futr_exog[:, :, -(self.label_len + self.h):, :]\n",
    "        else:\n",
    "            x_mark_enc = None\n",
    "            x_mark_dec = None\n",
    "\n",
    "\n",
    "        y_pred = self.forecast(insample_y, x_mark_enc, x_mark_dec)\n",
    "        y_pred = y_pred[:, -self.h:, :]\n",
    "        if self.loss.outputsize_multiplier > 1:\n",
    "            y_pred = self.distr_output(y_pred)\n",
    "\n",
    "        return y_pred\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(TimeMixer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(TimeMixer.fit, name='TimeMixer.fit')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(TimeMixer.predict, name='TimeMixer.predict')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# Unit tests for models\n",
    "logging.getLogger(\"pytorch_lightning\").setLevel(logging.ERROR)\n",
    "logging.getLogger(\"lightning_fabric\").setLevel(logging.ERROR)\n",
    "with warnings.catch_warnings():\n",
    "    warnings.simplefilter(\"ignore\")\n",
    "    check_model(TimeMixer, [\"airpassengers\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Usage example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| eval: false\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast import NeuralForecast\n",
    "from neuralforecast.models import TimeMixer\n",
    "from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic\n",
    "from neuralforecast.losses.pytorch import MAE\n",
    "\n",
    "Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 132 train\n",
    "Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test\n",
    "\n",
    "model = TimeMixer(h=12,\n",
    "                input_size=24,\n",
    "                n_series=2,\n",
    "                scaler_type='standard',\n",
    "                max_steps=500,\n",
    "                early_stop_patience_steps=-1,\n",
    "                val_check_steps=5,\n",
    "                learning_rate=1e-3,\n",
    "                loss = MAE(),\n",
    "                valid_loss=MAE(),\n",
    "                batch_size=32\n",
    "                )\n",
    "\n",
    "fcst = NeuralForecast(models=[model], freq='ME')\n",
    "fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12)\n",
    "forecasts = fcst.predict(futr_df=Y_test_df)\n",
    "\n",
    "# Plot predictions\n",
    "fig, ax = plt.subplots(1, 1, figsize = (20, 7))\n",
    "Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds'])\n",
    "plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1)\n",
    "plot_df = pd.concat([Y_train_df, plot_df])\n",
    "\n",
    "plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1)\n",
    "plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True')\n",
    "plt.plot(plot_df['ds'], plot_df['TimeMixer'], c='blue', label='median')\n",
    "ax.set_title('AirPassengers Forecast', fontsize=22)\n",
    "ax.set_ylabel('Monthly Passengers', fontsize=20)\n",
    "ax.set_xlabel('Year', fontsize=20)\n",
    "ax.legend(prop={'size': 15})\n",
    "ax.grid()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using `cross_validation` to forecast multiple historic values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| eval: false\n",
    "fcst = NeuralForecast(models=[model], freq='M')\n",
    "forecasts = fcst.cross_validation(df=AirPassengersPanel, static_df=AirPassengersStatic, n_windows=2, step_size=12)\n",
    "\n",
    "# Plot predictions\n",
    "fig, ax = plt.subplots(1, 1, figsize = (20, 7))\n",
    "Y_hat_df = forecasts.loc['Airline1']\n",
    "Y_df = AirPassengersPanel[AirPassengersPanel['unique_id']=='Airline1']\n",
    "\n",
    "plt.plot(Y_df['ds'], Y_df['y'], c='black', label='True')\n",
    "plt.plot(Y_hat_df['ds'], Y_hat_df['TimeMixer'], c='blue', label='Forecast')\n",
    "ax.set_title('AirPassengers Forecast', fontsize=22)\n",
    "ax.set_ylabel('Monthly Passengers', fontsize=20)\n",
    "ax.set_xlabel('Year', fontsize=20)\n",
    "ax.legend(prop={'size': 15})\n",
    "ax.grid()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
